package com.sparrow.manage.publish;

import com.sparrow.config.EnvironmentVariables;
import com.sparrow.manage.article.ArticleService;
import com.sparrow.manage.common.entity.result.Result;
import com.sparrow.manage.common.service.impl.AttachmentService;
import com.sparrow.manage.common.tree.TreeTable;
import com.sparrow.manage.common.tree.TreeTableElement;
import com.sparrow.manage.company.CompanyService;
import com.sparrow.manage.template.ThymeleafStaticize;
import com.sparrow.manage.template.data.ThymeleafDataContext;
import com.sparrow.manage.template.data.strategy.CommonDataFetch;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(EnvironmentVariables.MANAGE_ACCESS_PREFIX + "/publish")
public class PublishController {

    private static final String STATIC_TEMPLATE_PATH = EnvironmentVariables.FILE_RESOURCE_ROOT + "/templates";

    private static final ThymeleafStaticize statisticPage = new ThymeleafStaticize(STATIC_TEMPLATE_PATH + "/",
            EnvironmentVariables.TEMPLATE_SUFFIX,
            ThymeleafStaticize.ResolverPath.FILE_PATH);

    @Autowired
    private CompanyService companyService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private AttachmentService attachmentService;

    /**
     * 获取classpath下的所有模板资源
     * 由于是jar启动, 所以必须这么配置
     *
     * @return
     */
    private List<String> getTemplateListInClasspath() {
        List<String> templateNames = new ArrayList<>();

        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        try {
            Resource[] resources = resolver.getResources(STATIC_TEMPLATE_PATH + "/*.html");

            for (Resource resource : resources) {
                String filename = resource.getFilename();
                templateNames.add(filename.substring(0, filename.length() - 5));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return templateNames;
    }

    /**
     * 获取项目目录下的所有模板资源
     *
     * @return
     */
    private List<TreeTableElement<String>> getTemplateList(String path, String parentId) {
        List<TreeTableElement<String>> templateNames = new ArrayList<>();
        int suffixLength = EnvironmentVariables.TEMPLATE_SUFFIX.length();

        File directory = new File(path);
        if (directory.exists() && directory.isDirectory()) {
            File[] files = directory.listFiles();

            for (int i =0; i < files.length; i++) {
                File file = files[i];
                if(file.isFile()){
                    String fileName = file.getName();
                    if(fileName.endsWith(EnvironmentVariables.TEMPLATE_SUFFIX)){
                        TreeTableElement<String> element = new TreeTableElement<>();
                        element.setId(parentId + "_" + (i + 1));
                        element.setpId(String.valueOf(parentId));
                        element.setEntity(fileName.substring(0, fileName.length() - suffixLength));
                        templateNames.add(element);
                    }
                }else{
                    TreeTableElement<String> element = new TreeTableElement<>();
                    element.setEntity(file.getName());
                    element.setId(parentId + "_" + (i + 1));
                    element.setpId(String.valueOf(parentId));
                    element.setEntity(file.getName());
                    element.setLeaf(false);
                    templateNames.add(element);
                    List<TreeTableElement<String>> subTemplateNames = getTemplateList(file.getPath(), element.getId());
                    templateNames.addAll(subTemplateNames);
                }
            }
        }
        return templateNames;
    }

    @RequestMapping("index")
    public String index() {
        return EnvironmentVariables.MANAGE_TEMPLATE_STORE_PATH + "publish/index";
    }

    @RequestMapping("treeTable")
    @ResponseBody
    public TreeTable<String> treeTable(){
        List<TreeTableElement<String>> templateTree = getTemplateList(STATIC_TEMPLATE_PATH, "0");
        TreeTable<String> treeTable = new TreeTable<>();
        treeTable.setData(templateTree);
        return treeTable;
    }

    @RequestMapping("/doIt")
    @ResponseBody
    public Result publish(String template, HttpServletRequest request, HttpServletResponse response) {
        Result result = new Result();
        try {
            // 获取thymeleaf模板所需数据
            // 这里使用通用数据获取策略
            CommonDataFetch dataFetch = new CommonDataFetch();
            dataFetch.setCompanyService(companyService);
            dataFetch.setArticleService(articleService);
            dataFetch.setAttachmentService(attachmentService);

            // 策略上下文, 策略执行者
            ThymeleafDataContext strategyContext = new ThymeleafDataContext(dataFetch, request, response);

            // 生成模板
            statisticPage.statisticPage(strategyContext.generateTemplateContext(), template,  EnvironmentVariables.getPortalStaticPublishPath() + template + ".html");

            result.setSuccess(true);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

}
